package com.aiti.lulian.config;

import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.annotates.LoginUser;
import com.aiti.lulian.bo.LoginUserInfo;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * @description: LoginUser注解解析器，设置当前登录用户数据。
 *              若获取不到当前登录用户数据，则返回null
 * @auth fcb
 * @date 2025-03-04 15:34
 **/
public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        LoginUser methodAnnotation = parameter.getParameterAnnotation(LoginUser.class);
        if(methodAnnotation == null) {
            return false;
        }
        Class<?> parameterType = parameter.getParameterType();
        return LoginUserInfo.class.isAssignableFrom(parameterType);
    }

    /**
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        LoginUserInfo userInfo = new LoginUserInfo();
        String userId = this.findUserId(request);
        String userName = this.findUserName(request);
        userInfo.setUserName(userName);
        userInfo.setUserId(userId);
        return userInfo;
    }

    public String findUserId(HttpServletRequest request) {
        return request.getHeader("x-userid-header");
    }

    public String findUserName(HttpServletRequest request) {
        String userName = null;
        String header = request.getHeader("x-user-header");
        if (StringUtil.isNotEmpty(header)) {
            if (header.contains(":")) {
                String[] split = header.split(":");
                if (split.length > 1) {
                    userName = split[1];
                }
            } else {
                userName = header;
            }
        }

        return userName;
    }

}
